package com.quanshu.exchange.ui.gui.message.chat;

import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;

import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.config.Config;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.gui.message.chat.row.ChatMessageAdapter;
import com.scwang.smartrefresh.header.WaterDropHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by jye on 2017/12/7.
 */

public class ChatMessageList extends RelativeLayout {

    @BindView(R.id.chat_list)
    RecyclerView chatRecyclerView;
    @BindView(R.id.chat_refresh_layout)
    SmartRefreshLayout chatRefreshLayout;
    @BindView(R.id.chat_bg)
    RelativeLayout chatBg;
    private View view;

    public ChatMessageAdapter getAdapter() {
        return adapter;
    }

    private ChatMessageAdapter adapter;
    private LinearLayoutManager linearLayoutManager;
    private Context context;
    private EMConversation conversation;

    protected boolean isloading;
    protected boolean haveMoreData = true;

    public ChatMessageList(Context context) {
        super(context);
        init(context);
    }

    public ChatMessageList(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ChatMessageList(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public ChatMessageList(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    private void init(Context context) {
        this.context = context;
        view = LayoutInflater.from(context).inflate(R.layout.view_chat_message, this);
        ButterKnife.bind(view);
        linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setStackFromEnd(true);
        chatRecyclerView.setLayoutManager(linearLayoutManager);
        chatRefreshLayout.setRefreshHeader(new WaterDropHeader(context));
        chatRefreshLayout.setOnRefreshListener(refreshlayout -> loadMoreLocalMessage());
    }

    public void setConversation(EMConversation conversation, String groupOwner) {
        this.conversation = conversation;
        adapter = new ChatMessageAdapter(context, conversation, groupOwner, chatRecyclerView, view);
        chatRecyclerView.setAdapter(adapter);
        refreshSelectLast();
    }

    /**
     * refresh
     */
    public void refresh() {
        if (adapter != null) {
            adapter.refreshList();
        }
    }

    /**
     * 0: 非公开群 ，1：公开群
     *
     * @param flag
     */
    public void setChatBackground(int flag) {
        if (flag == 0) {
            chatBg.setBackgroundResource(R.drawable.shape_chat_bg_gray);
        } else {
            chatBg.setBackgroundResource(R.drawable.chat_bg_open);
        }
    }

    /**
     * refresh and jump to the last
     */
    public void refreshSelectLast() {
        if (adapter != null) {
            adapter.refreshToLast();
        }
    }

    private void loadMoreLocalMessage() {
        if (adapter == null) {
            return;
        }
        linearLayoutManager.setStackFromEnd(false);
        if (linearLayoutManager.findFirstVisibleItemPosition() == 0 && haveMoreData) {
            List<EMMessage> messages;
            try {
                messages = conversation.loadMoreMsgFromDB(conversation.getAllMessages().size() == 0 ? "" : conversation.getAllMessages().get(0).getMsgId(),
                        Config.Chat_MSG_PAGE);
            } catch (Exception e1) {
                chatRefreshLayout.finishRefresh(1000/*,false*/);//传入false表示加载失败
                return;
            }
            if (messages.size() > 0) {
                refresh();
                if (messages.size() != Config.Chat_MSG_PAGE) {
                    haveMoreData = false;
                }
            } else {
                haveMoreData = false;
            }

            isloading = false;
        } else {
            ToastHelper.toast(getResources().getString(R.string.no_more_messages));
        }
        chatRefreshLayout.finishRefresh(1000/*,false*/);//传入false表示加载失败
    }

}


